//页面级视图-存储卡读取权限
import React from 'react';
import {View, Alert} from 'react-native';
import {useDebounceEffect, useMount, useSafeState, useUnmount} from 'ahooks';
import {Text, Button} from '@rneui/base';
import {
  check,
  checkMultiple,
  request,
  PERMISSIONS,
  openSettings,
  RESULTS,
} from 'react-native-permissions';

import RNFS from 'react-native-fs';
import RNFetchBlob from 'react-native-blob-util';
import {Dirs, FileSystem} from 'react-native-file-access';

import READ_EXTERNAL_STORAGE from './READ_EXTERNAL_STORAGE';
import WRITE_EXTERNAL_STORAGE from './WRITE_EXTERNAL_STORAGE';
import dayjs from 'dayjs';

const checkObjs = {
  READ_EXTERNAL_STORAGE,
  WRITE_EXTERNAL_STORAGE,
};

export default ({children}) => {
  const [loading, setLoading] = useSafeState(true);
  const [Coms, setComs] = useSafeState([]);

  const updateComs = async () => {
    const newComs = [];
    for (const [key, Com] of Object.entries(checkObjs)) {
      let v = '';
      try {
        v = await check(PERMISSIONS.ANDROID[key]);
      } catch (e) {
        v = 'denied';
      }
      const isAllow = v === RESULTS.GRANTED;
      if (!isAllow) {
        console.log(key, v);
        newComs.push(Com);
      }
    }
    setComs(newComs);
    setLoading(false);
  };
  useMount(() => {
    updateComs();
  });
  if (loading) {
    return <Text></Text>;
  }
  if (Coms.length > 0) {
    return (
      <View
        style={{
          flex: 1,
          alignItems: 'center',
          justifyContent: 'center',
        }}>
        <Text>使用网盘需要授权：</Text>
        {Coms.map((Item, index) => (
          <Item
            key={index}
            callback={() => {
              updateComs();
            }}
          />
        ))}
      </View>
    );
  }
  return children;
};
